<?php

namespace ASW\Utility\Logging\Providers;

use ASW\Utility\ColorTerminal\Terminal;
use ASW\Utility\ColorTerminal\TerminalForeground;
use ASW\Utility\Logging\ILogProvider;
use ASW\Utility\Logging\LogLevel;
use Throwable;

class TerminalLogProvider implements ILogProvider
{
    public function __construct(private readonly LogLevel $minLevel = LogLevel::DEBUG)
    {

    }

    public function log(LogLevel $logLevel, string $category, string $message, Throwable $throwable = null): void
    {
        if (PHP_SAPI !== 'cli') return;
        if ($logLevel->value < $this->minLevel) return;

        $timePart      = date('H:i:s');
        $levelPart     = str_pad($logLevel->name, 6);
        $throwablePart = empty($throwable) ? '' : "\r\nthrow: \r\n" . $throwable->getTraceAsString();
        $logContent    = "$timePart | $levelPart | $message$throwablePart";

        $logColor = self::getLogLevelColor($logLevel);

        Terminal::create()->color($logColor)->echo("$logContent")->echo("\r\n");
    }

    public static function getLogLevelColor(LogLevel $logLevel): TerminalForeground
    {
        return match ($logLevel) {
            LogLevel::DEBUG => TerminalForeground::TXT_COLOR_PURPLE,
            LogLevel::INFO => TerminalForeground::TXT_COLOR_CYAN,
            LogLevel::WARN => TerminalForeground::TXT_COLOR_BROWN,
            LogLevel::ERROR => TerminalForeground::TXT_COLOR_RED,
        };
    }
}